import {defineStore} from "pinia";
import {getInfo, login, logout} from "@/api/login";
import {getToken, removeToken, setToken} from "@/utils/auth.js";
import usePermissionStore from "@/store/modules/permission";


const useUserStore = defineStore('user', {
    // 为了完整类型推理，推荐使用箭头函数
    state: () => ({
        user: {},
        permissions:[],
        needRefreshInfo: false
    }),
    actions: {
        // 登录
        login(userName, password) {
            return new Promise((resolve, reject) => {
                login(userName, password)
                    .then(res => {
                        setToken(res.data.token)
                        resolve(res)
                    }).catch(err => reject(err))
            })
        },
        // 获取用户信息
        getInfo() {
            return new Promise((resolve, reject) => {
                getInfo().then(res => {
                    this.user = res.data.userInfo
                    this.permissions = res.data.permissions
                    resolve(res.data)
                }).catch(err => reject(err))
            })
        },
        // 退出登录
        logout() {
            return new Promise((resolve, reject) => {
                logout().then(res => {
                    removeToken()
                    this.user = {}
                    this.needRefreshInfo = true
                    resolve(res)
                }).catch(err => reject(err))
            })
        }
    }
})

export default useUserStore
